<template>
	<view class="page" style="height: 100%;">
		<PageHeader :showPlaceHolder="false" :customTitle="customTitle"></PageHeader>
		<view class="page-content" style="height: 100%;">
			<view class="page ui-form-basic page-price">
				<view class="page-tips" v-if="isSetPrice">
					<fui-icon name="info" size="28" color="#f98900"></fui-icon>
					<fui-text text="如已设置按统一比例上浮售价，可针对单独的商品进行自定义售价" size="24" color="#f98900"></fui-text>
				</view>
				<view class="" v-if="isSetPrice">
					<view class="price-subtitle">调整规则</view>
					<fui-form ref="formRef" :model="form" :show='false' class="form-wrapper" labelWidth="160"
						labelSize="28" labelWeight="bold">
						<fui-form-item label="规则类型" arrow left="0" :bottomBorder="false" marginBottom="24"
							:padding="['16rpx', 0]" @click="onShowTypePicker">
							<fui-input :borderBottom="false" :padding="[0]" placeholder="请选择规则" v-model="form.type"
								size="28" disabled></fui-input>
						</fui-form-item>
						<fui-form-item v-if="form.type === '统一比例'" label="上浮比例" prop="floatRatio" left="0"
							:bottomBorder="false" :padding="['16rpx', 0]">
							<fui-input :borderBottom="false" type='digit' number :padding="[0]" placeholder="请输入上浮比例"
								v-model="form.floatRatio" size="28" @input="onChangeFloatRatio"></fui-input>
							<template v-slot:right>
								<fui-text text="%" size="28" fontWeight="bold"></fui-text>
							</template>
						</fui-form-item>
						<fui-form-item v-if="form.type === '统一价格'" label="上浮价格" prop="floatValue" left="0"
							:bottomBorder="false" :padding="['16rpx', 0]">
							<fui-input :borderBottom="false" type='digit' number :padding="[0]" placeholder="请输入上浮价格"
								v-model="form.floatValue" size="28" @input="onChangeFloatValue"></fui-input>
							<template v-slot:right>
								<fui-text text="元" size="28" fontWeight="bold"></fui-text>
							</template>
						</fui-form-item>
					</fui-form>
					<view class="price-subtitle">价格组</view>
					<view class="price-wrapper" :class="{'price-change': form.type === '单独比例'}">
						<view class="price-list" v-for="(item, index) in pricesList" :key="item.id">
							<view class="price-item" style="flex: 0 0 100%;">
								<fui-text text="起售数量：" size="24" color="#666"></fui-text>
								<fui-text class="price-item-value" :text="item.startNum" size="24" color="#333"></fui-text>
								<fui-text :text="unit" size="24" color="#333"></fui-text>
							</view>
							<view class="price-item" style="flex: 0 0 100%;">
								<fui-text text="原始价格：" size="24" color="#666"></fui-text>
								<fui-text text="¥" size="24" color="#666"></fui-text>
								<fui-text class="price-item-value" :text="utils.moneyFormatter(item.originPrice)" size="24" color="#333"></fui-text>
								<fui-text :text="`/${unit}`" size="24" color="#333"></fui-text>
							</view>
							<view class="price-item" style="flex: 0 0 100%;" v-if="form.type === '单独比例'">
								<fui-text text="上浮比例：" size="24" color="#666"></fui-text>
								<fui-text text="¥" size="28" color="#333" fontWeight="bold"></fui-text>
								<fui-input type='digit' number v-model="item.jjbl" class="price-item-value"
									:borderBottom="false" :padding="[0]" size="24" :max="999999" @input="onChangeFloatRatioItem($event, index)"></fui-input>
								<fui-text text="%" size="24" color="#333"></fui-text>
							</view>
							<view class="price-item" style="flex: 0 0 100%;">
								<fui-text text="销售价格：" size="24" color="#666"></fui-text>
								<fui-text text="¥" size="28" color="#E9574F" fontWeight="bold"></fui-text>
								<fui-text class="price-item-value" :text="utils.moneyFormatter(item.price)"
									size="28" color="#E9574F" fontWeight="bold"></fui-text>
								<fui-text :text="`/${unit}`" size="24" color="#E9574F" fontWeight="bold"></fui-text>
							</view>
							<view class="price-item" v-if="item.errMsg">
								<fui-text :text="item.errMsg" size="24" color="#E9574F"></fui-text>
							</view>
							<!-- <view class="price-item">
								<fui-text text="成本价格：" size="24" color="#666"></fui-text>
								<fui-text text="¥" size="28" color="#E9574F" fontWeight="bold"></fui-text>
								<fui-text class="price-item-value" :text=" utils.moneyFormatter(item.costPrice)" size="28" color="#E9574F" fontWeight="bold">
                </fui-text>
								<fui-text :text="`/${unit}`" size="24" color="#E9574F" fontWeight="bold"></fui-text>
							</view> -->
						</view>
					</view>
				</view>

				<!-- 改价 -->
				<view class="" v-else>
					<view class="price-subtitle">价格组</view>
					<view class="price-wrapper price-change">
						<view class="price-list" v-for="item in pricesList" :key="item.id">
							<view class="price-item">
								<fui-text text="起售数量：" size="24" color="#666"></fui-text>
								<fui-input type='number' number v-model="item.startNum" class="price-item-value prices-change"	:borderBottom="false" :padding="[0]" size="24">
                </fui-input>
								<fui-text :text="unit" size="24" color="#333"></fui-text>
							</view>
							<view class="price-item">
								<fui-text text="起售价格：" size="24" color="#666"></fui-text>
								<fui-text text="¥" size="28" color="#333" fontWeight="bold"></fui-text>
								<fui-input type='digit' number v-model="item.price" class="price-item-value prices-change"
									:borderBottom="false" :padding="[0]" size="24" @input="onChangeDigit($event, item, 'price')"></fui-input>
								<fui-text :text="`/${unit}`" size="24" color="#333"></fui-text>
							</view>
							<!-- <view class="price-item">
								<fui-text text="成本价格：" size="24" color="#666"></fui-text>
								<fui-text text="¥" size="28" color="#333" fontWeight="bold"></fui-text>
								<fui-input type='digit' number v-model="item.costPrice" class="price-item-value prices-change"
									:borderBottom="false" :padding="[0]" size="24" @input="onChangeDigit($event, item, 'costPrice')"></fui-input>
								<fui-text :text="`/${unit}`" size="24" color="#333"></fui-text>
							</view> -->
						</view>
					</view>
				</view>

				<view class="btn-wrapper">
					<fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx"
						:margin="['0', '54rpx', '0', '0']" @click="cancel"></fui-button>
					<fui-button :text="isSetPrice ? '保存并通过' : '保存'" height="78rpx" radius="8rpx" :margin="['0']" :loading="isLoading"
						@click="submit"></fui-button>
				</view>
			</view>

			<!-- 规则 -->
			<fui-picker :options="typeOptions" :show="showTypePicker" @change="changeType"
				@cancel="showTypePicker = false"></fui-picker>
		</view>
	</view>
</template>

<script setup>
	import PageHeader from '@/components/header';
	import {ref, reactive, computed, inject, watch } from 'vue'
	import { onLoad	} from '@dcloudio/uni-app'
	import goodsApi from '@/api/goods';
	import { useStore	} from 'vuex';
	import utils from '@/components/firstui/fui-utils'
	const store = useStore();
	const tab = inject('$tab')
	const modal = inject('$modal');

	const formRef = ref(null)
	const form = ref({
		type: '统一比例',
		floatRatio: '', //上浮比例 
		floatValue: '' //上浮价格
	})

	const showTypePicker = ref(false)
	const typeOptions = ['统一比例', '单独比例']
	const onShowTypePicker = () => {
		showTypePicker.value = true
	}

	// 规则类型改变
	const changeType = (e) => {
		showTypePicker.value = false
		form.value = {
			type: e.result,
			floatRatio: '',
			floatValue: ''
		}
		pricesList.value = JSON.parse(JSON.stringify(initPricesList.value))
	}

	const productId = ref('')
	const isSetPrice = ref(true) //true是设置售价，false是改价
	const defaultRatio = ref('') // 默认上浮比例
	const customTitle = ref('设置售价')
	const unit = ref('')
	const pricesList = ref('') //价格组
	const initPricesList = ref('') //初始化价格组，用于比价

	onLoad((option) => {
		productId.value = option.productId
		isSetPrice.value = JSON.parse(option.isSetPrice) //true是设置收件，false是改价
		unit.value = option.unit || '' //单位
		customTitle.value = isSetPrice.value ? "设置售价" : "改价" //标题
		//详情中的价格组
		pricesList.value = JSON.parse(JSON.stringify(store.getters.detailOriginData.prices))
		initPricesList.value = JSON.parse(JSON.stringify(store.getters.detailOriginData.prices))
    pricesList.value.forEach(item => {
			item.originPrice = item.price / 100
      item.price = item.price / 100
      item.costPrice = item.costPrice / 100
    })
    initPricesList.value.forEach(item => {
			item.originPrice = item.price / 100
      item.price = item.price / 100
      item.costPrice = item.costPrice / 100
    })
		if (isSetPrice.value) {
			defaultRatio.value = JSON.parse(option.defaultRatio)
			onChangeFloatRatio(defaultRatio.value)
		}
	})

	const rules = ref([])
	// 根据规则类型，动态设置rules
	watch(
		() => form.value.type,
		() => {
			if (form.value.type === '统一比例') {
				rules.value = [{
					name: 'floatRatio',
					rule: ['required'],
					msg: ['请输入上浮比例']
				}]
			} else if (form.value.type === '统一价格') {
				rules.value = [{
					name: 'floatValue',
					rule: ['required'],
					msg: ['请输入上浮价格']
				}]
			} else {
				rules.value = []
			}
		}, {
			immediate: true
		})

	// 监听上浮比例变化
	const onChangeFloatRatio = async (value) => {
		if (value < 0) {
			modal.msgError('上浮比例必须大于等于0！')
			form.value.floatRatio = await ''
		} else if (value > 30) {
			modal.msgError('上浮比例不能超过原始价格的30%，请重新设置！')
			form.value.floatRatio = await ''
		} else {
			form.value.floatRatio = await value == '' ? '' : value * 1
		}
		pricesList.value = initPricesList.value.map((item) => {
			const newPrice = (1 + form.value.floatRatio * 1 / 100) * item.price;
			return {
				...item,
				price: newPrice.toFixed(2),
				jjbl: form.value.floatRatio
			}
		})
	}

	// 监听上浮价格变化
	const onChangeFloatValue = () => {
		const minPrice = Math.min(...initPricesList.value.map(item => item.price))
		if (form.value.floatValue < 0) {
			modal.msgError('上浮价格必须大于等于0！')
			form.value.floatValue = ''
		} else if (form.value.floatValue > minPrice * 0.3) {
			modal.msgError('上浮价格不能超过原始价格最小值的30%，请重新设置！')
			form.value.floatValue = ''
		}
		pricesList.value = initPricesList.value.map((item) => {
			const newPrice = 1 * form.value.floatValue + 1 * item.price;
			return {
				...item,
				price: newPrice.toFixed(2)
			}
		})
	}

	// 单独比例设置
	const onChangeFloatRatioItem = async (value, index) => {
		if (value < 0) {
			pricesList.value[index].errMsg = '上浮比例必须大于等于0！'
			pricesList.value[index].jjbl = await ''
			pricesList.value[index].price = initPricesList.value[index].price
		} else if (value > 30) {
			pricesList.value[index].errMsg = '上浮比例不能超过原始价格的30%，请重新设置！'
			pricesList.value[index].jjbl = await ''
			pricesList.value[index].price = initPricesList.value[index].price
		} else {
			pricesList.value[index].errMsg = ''
			pricesList.value[index].jjbl = await value == '' ? '' : value * 1
			const newPrice = (1 + (pricesList.value[index].jjbl ? pricesList.value[index].jjbl * 1 / 100 : 0)) * initPricesList.value[index].price
			pricesList.value[index].price = newPrice
		}
	}

	// 改价
	const onChangeDigit = async (value, obj, feild) => {
		if (value <= 0) {
			modal.msgError('价格必须大于0！')
			obj[feild] = await ''
		} else {
			obj[feild] = await value == '' ? '' : value * 1
		}
	}

	// 保存
	const isLoading = ref(false)
	const submit = async () => {
		if (isSetPrice.value) {
			if (pricesList.value.findIndex(item => !item.jjbl || item.errMsg) > -1) {
				modal.msgError('售价设置不完整，请检查！');
				return
			}
			const res = await formRef.value.validator(form.value, rules.value)
			if (res.isPassed) {
				setPrice() //设置售价
			} else {
				modal.msgError(res.errorMsg);
			}
		} else {
			changePrices() //改价
		}
	}

	//设置售价
	const setPrice = () => {
		modal.confirm('您确认要保存售价设置并通过供应商申请吗？').then(() => {
			examineGoods()
			// 暂时改变详情的值，正式更改数据库需要再详情点击通过
      // const prices = pricesList.value.map(item => {
      //   return {
      //     ...item,
      //     price: (item.price * 100).toFixed(0),
      //     costPrice: (item.costPrice * 100).toFixed(0)
      //   }
      // })
			// const newDetailData = {
			// 	...JSON.parse(JSON.stringify(store.getters.detailData)),
			// 	prices
			// }
			// uni.$emit('onSetPrices', prices)
			// store.commit('SET_DETAIL_DATA', newDetailData)
			// store.commit('SET_DETAIL_AGREE', true)
			// setTimeout(() => {
			// 	uni.navigateBack({
			// 		delta: 1
			// 	})
			// }, 500)
		})
	}

	// 审核上架
	const examineGoods = () => {
		try {
			const editPrices = pricesList.value.map(item => {
        return {
          pricesId: item.id,
					priceAfter: (item.price * 100).toFixed(0),
					jjbl: item.jjbl * 1
        }
      })
			// console.log(editPrices)
			// return
			goodsApi.doAudit({
				id: productId.value, //商品id
				auditState: 1,
				editPrices: editPrices
			}).then((res) => {
				if (res.code === 0) {
					if (res.data == -1) {
						modal.msgSuccess('供应商处于停用状态！')
					} else {
						modal.msgSuccess('商品已通过审核！')
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							})
						}, 500)
					}
				} else {
					modal.msgError(res.msg)
				}
			})
		} catch (e) {
			console.log('examineGoods ===>', e);
		}
	}

	//改价
	const changePrices = () => {
		let flag = true
		let errString = ''
		try {
			pricesList.value.forEach((item) => {
				flag = true
				if (!item.startNum && flag) {
					errString = '请输入起售数量'
					flag = false
				}
				if (!item.price && flag) {
					errString = '请输入起售价格'
					flag = false
				}
        if(!Number.isInteger(item.startNum)){
          errString = '起售数量不能是小数'
          flag = false
        }
				if (!item.costPrice && flag) {
					errString = '请输入成本价格'
					flag = false
				}
				if (!flag) {
					modal.msgError(errString)
					throw new Error();
				}
			})
		} catch (e) {

		}

		try {
			if (flag) {
				modal.confirm('您确认要保存更改的价格吗？').then(() => {
          const prices = pricesList.value.map(item => {
            return {
              ...item,
              price: (item.price * 100).toFixed(0),
              costPrice:(item.costPrice * 100).toFixed(0)
            }
          })
          console.log("aaaaaaaaaa",prices)
					goodsApi.changePrices({
						prices
					}).then((res) => {
						if (res.code === 0) {
							modal.msgSuccess('改价成功')
							store.commit('SET_REFRESH_DETAIL_FLAG', !store.getters.refreshDetailFlag) //刷新详情页
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 500)
						} else {
							modal.msgError(res.msg)
						}
					})
				})
			}
		} catch (e) {
			console.log('changePrices ===>', e);
		}
	}

	const cancel = () => {
		tab.navigateBack()
	}
</script>

<style lang="scss" scoped>
	@import "@/static/scss/form.scss";

	.page-tips {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		.fui-icon {
			margin-right: 10rpx;
		}
	}

	.page-price {
		.price-subtitle {
			margin-bottom: 18rpx;
			font-size: 28rpx;
			font-weight: bold;
			color: #333333;
		}

		.form-wrapper {
			background-color: transparent;
			margin-bottom: 24rpx;
			padding: 0 !important;

			.fui-form__item-wrap {
				border-radius: 16rpx !important;
				padding: 4rpx 28rpx;
			}
		}

		.price-wrapper {
			border-radius: 16rpx;
			background-color: #fff;
			margin-bottom: 118rpx;
			padding: 24rpx 20rpx;

			&.price-change {
				background-color: transparent;
				padding: 0;

				.price-list {
					background-color: #fff;
				}
			}


			.price-list {
				border-radius: 12rpx;
				background-color: #f1f7fe;
				padding: 22rpx 44rpx 10rpx;

				&:not(:last-child) {
					margin-bottom: 16rpx;
				}

				.price-item {
					display: flex;
					margin-bottom: 12rpx;

					.price-item-value {
						margin: 0 6rpx;

						:deep(.fui-input__self) {
							text-align: center !important;
							padding: 0 !important;
						}
					}

					// 改价
					.prices-change {
						:deep(.fui-input__self) {
							color: #E9574F !important;
							font-weight: bold !important;
						}
					}


					.fui-input__wrap {
						flex: 0 0 160rpx;
						border-bottom: 2rpx solid #707070;
						border-radius: 0 !important;
					}
				}
			}
		}
	}
</style>